package com.alibaba.moco.didi;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.moco.util.BaseTypeUtil;
import groovy.util.ResourceException;
import groovy.util.ScriptException;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;

import com.alibaba.moco.MocoScriptRunner;

import net.sf.json.JSONObject;

public class MocoHandle extends ResourceHandler {
	
	private static String PATH_SCRIPT="script";
	
	@SuppressWarnings("unused")
	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		super.handle(target, baseRequest, request, response);
		String exeFile = PATH_SCRIPT;
		exeFile+=request.getRequestURI();
		if(exeFile == null && exeFile.equals(PATH_SCRIPT)){
			return;
		}
        Object result = null;
        File groovyfile  = new File(BaseTypeUtil.getClassPath() + exeFile + ".groovy" );
        File jsonfile  = new File(BaseTypeUtil.getClassPath() + "json" + request.getRequestURI() + ".json" );
        if (jsonfile.exists()){
            result = MocoScriptRunner.excuteJson("json"+request.getRequestURI());
        } else if (groovyfile.exists()){
            try {
                result = MocoScriptRunner.excuteScript(request,exeFile);
            } catch (ResourceException e) {
                e.printStackTrace();
            } catch (ScriptException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        response.setContentType("text/json");
		response.setCharacterEncoding("utf-8");
		
		response.getWriter().write(JSONObject.fromObject(result).toString());
		response.getWriter().flush();
		response.getWriter().close();
	}

}
